<?php

class LuaConverter{

  private $variables;
  private $debug;

  function __construct($dbg = false){
    $this->variables = null;
    $this->debug = $dbg;
  }
  

  public function convert($lua_text){
    if((explode("\n", $lua_text)) > 0){
      $result = array();
	  $lua_text = str_replace("--", "//", $lua_text);
      $lua_text =  str_replace(",\n)", "\n)",
                    str_replace("{", "array(",
                     str_replace("}", ");",
                      str_replace("},", "),",
                       str_replace("[", "",
                        str_replace("] = ", " => ",
                         str_replace("\t", "", 
                          str_replace("{\n}", "false\n", $lua_text )
                 )
                )
                       )
                      )
                     )
                    )
                   );
      foreach(explode("\n", $lua_text) as $lua_line){
	    if($this->debug){print($lua_line."\n");}
	    $lua_line = chop($lua_line);
	    if(preg_match("/^[a-z]/", $lua_line)){
	      if(is_numeric($lua_line[strlen($lua_line)-1]) || $lua_line[strlen($lua_line)-1] == "\""){
	        $lua_line.=";";
	      }
		  if (substr($lua_line, -3) == "nil")
		  {
			$lua_line = substr($lua_line, 0, -3) . "false;";
		  }
	      if($this->debug){print("variable start: $lua_line\n");}
	      
	      $result[] = "$".$lua_line;
	      $this->variables[] = substr($lua_line, 0, strpos($lua_line, " "));
	    }else{
	      $result[] = $lua_line;
	    }
      }
    }
    return implode("\n", $result);
  }

  public function getVariables(){
    return $this->variables;
  }

  public function variableCount(){
    return(count($this->variables));
  }
} 